
package cn.com.xy.sms.sdk.db.entity;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.StringUtils;
/*SDK-654 hewengao 20161026 start*/
import cn.com.xy.sms.sdk.title.SmsTitleManager;
import java.util.HashMap;
import org.json.JSONObject;
/*SDK-654 hewengao 20161026 end*/
public class SceneRuleManager {

    public static final String ID = "id";

    public static final String SCENERULEVERSION = "sceneRuleVersion";

    public static final String SCENE_ID = "scene_id";

    public static final String PROVINCE = "province";

    public static final String OPERATOR = "operator";

    public static final String EXPIRE_DATE = "expire_date";

    public static final String FUNC_CALL = "Func_call";

    public static final String FUNC_ACC_URL = "Func_acc_url";

    public static final String FUNC_REPLY_SMS = "Func_reply_sms";

    public static final String FUNC_CONFIG = "Func_config";

    public static final String RES_URLS = "res_urls";

    public static final String S_VERSION = "s_version";

    public static final String SCENE_PAGE_CONFIG = "Scene_page_config";

    public static final String ISDOWNLOAD = "isdownload";

    public static final String TABLE_NAME = "tb_scenerule_config";
    
	public static final String SCENETYPE = "sceneType";//0:弹窗 1:汽泡
    /* SDK-632 hewengao 20161009 start*/
    public static final String ISUSE ="isuse";//0:未使用 1：使用
    public static final String lAST_UPDATE_TIME ="last_update_time";//最后更新时间
    /* SDK-632 hewengao 20161009 end*/
    /*SDK-654  hewengao 20161026 start*/
    public static final String SCENE_RULE_CONFIG ="scene_rule_config";
    /*SDK-654    hewengao 20161026 end*/
    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;
    /* SDK-632 hewengao 20161009 start*/
    public static final String CREATE_TABLE = "create table  if not exists " + TABLE_NAME + " (" + ID + " TEXT," + SCENERULEVERSION + " TEXT," + SCENE_ID + " TEXT," + PROVINCE + " TEXT," + OPERATOR
            + " TEXT," + EXPIRE_DATE + " TEXT," + FUNC_CALL + " INTEGER," + FUNC_ACC_URL + " INTEGER," + FUNC_REPLY_SMS + " INTEGER," + FUNC_CONFIG + " TEXT," + RES_URLS + " TEXT," + S_VERSION
            + " TEXT," + SCENE_PAGE_CONFIG + " TEXT,"    + SCENETYPE+" INTEGER DEFAULT '-1',"
            /*SDK-654    hewengao 20161026 start*/
            + SCENE_RULE_CONFIG+" TEXT,"
            /* SDK-654   hewengao 20161026 end*/
            + ISDOWNLOAD + " INTEGER DEFAULT '0',"
            + ISUSE + " INTEGER DEFAULT 0,"
            + lAST_UPDATE_TIME + "  INTEGER DEFAULT 0"
            + ")";
     /* SDK-632 hewengao 20161009 end*/

    public static final String ADD_ISDOWNLOAD = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + ISDOWNLOAD + " INTEGER DEFAULT '0'";
    /* SDK-632 hewengao 20161009 start*/
    public static final String ADD_ISUSE = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + ISUSE + " INTEGER DEFAULT 0";
    public static final String ADD_lAST_UPDATE_TIME = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + lAST_UPDATE_TIME + " INTEGER DEFAULT 0";
     /* SDK-632 hewengao 20161009 end*/

     /* SDK-654  hewengao 20161026 start*/
     public static final String ADD_SCENE_RULE_CONFIG= "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + SCENE_RULE_CONFIG + "  TEXT";
     public static final String CREATE_SCENE_AND_TYPE_IDX = "create index if not exists scene_and_type_idx on "
            + TABLE_NAME + " (" + SCENE_ID + "," + SCENETYPE + ")";
    /* SDK-654  hewengao 20161026 end*/
    public static List<SceneRule> queryAllSceneRule(int sceneType,long periodTime) {
        List<SceneRule> sceneRuleList = new ArrayList<SceneRule>();
        XyCursor cur = null;
        try {
        	String sqlWhere="";
			if(sceneType == SceneconfigManager.SCENE_TYPE_BUBBLE){
				sqlWhere = SCENETYPE+" = "+sceneType;
			}else{
				sqlWhere = SCENETYPE+" != "+SceneconfigManager.SCENE_TYPE_BUBBLE;
			}
             /* SDK-632 hewengao 20161009 start*/
            sqlWhere = sqlWhere +" and "+ISUSE+" = 1";
            long time = System.currentTimeMillis()-periodTime;
            //当前时间-周期时间>最后更新时间
            sqlWhere = sqlWhere +" and "+lAST_UPDATE_TIME+" < "+time;
             /* SDK-632 hewengao 20161009 end*/
            cur = DBManager.query(TABLE_NAME, new String[] {
                ID, SCENE_ID, PROVINCE, OPERATOR, EXPIRE_DATE, FUNC_CALL, FUNC_ACC_URL, FUNC_REPLY_SMS, FUNC_CONFIG, RES_URLS, S_VERSION, SCENE_PAGE_CONFIG, ISDOWNLOAD,SCENERULEVERSION
            }, sqlWhere, null);
            if (cur != null && cur.getCount() > 0) {
                int idIndex = cur.getColumnIndex(ID);
                int sceneIdIndex = cur.getColumnIndex(SCENE_ID);
                int provinceIndex = cur.getColumnIndex(PROVINCE);
                int operatorIndex = cur.getColumnIndex(OPERATOR);
                int dateIndex = cur.getColumnIndex(EXPIRE_DATE);
                int callIndex = cur.getColumnIndex(FUNC_CALL);
                int accUrlIndex = cur.getColumnIndex(FUNC_ACC_URL);
                int replySmsIndex = cur.getColumnIndex(FUNC_REPLY_SMS);
                int configIndex = cur.getColumnIndex(FUNC_CONFIG);
                int urlsIndex = cur.getColumnIndex(RES_URLS);
                int versionIndex = cur.getColumnIndex(S_VERSION);
                int pageConfigIndex = cur.getColumnIndex(SCENE_PAGE_CONFIG);
                int isdownloadIndex = cur.getColumnIndex(ISDOWNLOAD);
                int sceneRuleVersionIndex = cur.getColumnIndex(SCENERULEVERSION);

                SceneRule tempConfig = null;
                while (cur.moveToNext()) {
                    tempConfig = new SceneRule();
                    tempConfig.id = cur.getString(idIndex);
                    tempConfig.scene_id = cur.getString(sceneIdIndex);
                    tempConfig.province = cur.getString(provinceIndex);
                    tempConfig.operator = cur.getString(operatorIndex);
                    tempConfig.expire_date = cur.getString(dateIndex);
                    tempConfig.Func_call = cur.getInt(callIndex);
                    tempConfig.Func_acc_url = cur.getInt(accUrlIndex);
                    tempConfig.Func_reply_sms = cur.getInt(replySmsIndex);
                    tempConfig.Func_config = cur.getString(configIndex);
                    tempConfig.res_urls = cur.getString(urlsIndex);
                    tempConfig.s_version = cur.getString(versionIndex);
                    tempConfig.Scene_page_config = cur.getString(pageConfigIndex);
                    tempConfig.isDownload = cur.getInt(isdownloadIndex);
                    tempConfig.sceneruleVersion= cur.getString(sceneRuleVersionIndex);

                    sceneRuleList.add(tempConfig);
                }

            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryAllSceneRule: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return sceneRuleList;
    }

    public static void updateIsdownload(SceneRule sceneRule, int isdownload) {
        try {
            if (sceneRule != null) {
                ContentValues values = new ContentValues();
                values.put(ISDOWNLOAD, isdownload);
                DBManager.update(TABLE_NAME, values, ID + " = ? ", new String[] {
                    sceneRule.id
                });
            }

        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "updateIsdownload error:", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {

        }
    }
    
    public static int updateTag(int tag){
        try {
            ContentValues values = new ContentValues();
            values.put(FUNC_CALL, tag);
            return DBManager.update(TABLE_NAME, values, null, null);
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "updateTag error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } 
        return -1;
    }

    public static List<SceneRule> querySceneRuleBySceneId(String sceneId, int sceneType) {
        return querySceneRuleBySceneId(sceneId, sceneType, false);
    }
     
    public static List<SceneRule> querySceneRuleBySceneId(String sceneId, int sceneType, boolean typeAndChannelFilter) {
        List<SceneRule> sceneRuleList = new ArrayList<SceneRule>();
        XyCursor cur = null;
        try {
            String sqlWhere = "";

            if (typeAndChannelFilter && sceneId.length() == 8) {
                sqlWhere = SCENE_ID + " LIKE '" + sceneId.substring(0, 2) + "%" + sceneId.substring(5, 8) + "' ";
            } else {
                sqlWhere = SCENE_ID + " = '" + sceneId + "' ";
            }

            if (sceneType == SceneconfigManager.SCENE_TYPE_BUBBLE) {
                sqlWhere = sqlWhere + " and " + SCENETYPE + " = " + sceneType;
            } else {
                sqlWhere = sqlWhere + " and " + SCENETYPE + " != " + SceneconfigManager.SCENE_TYPE_BUBBLE;
            }
                /*SDK-654   hewengao 20161026 start*/
            cur = DBManager.query(TABLE_NAME, new String[] { ID, SCENE_ID, PROVINCE, OPERATOR, EXPIRE_DATE, FUNC_CALL,
                    FUNC_ACC_URL, FUNC_REPLY_SMS, FUNC_CONFIG, RES_URLS, S_VERSION, SCENE_PAGE_CONFIG, ISDOWNLOAD,
                    SCENERULEVERSION,SCENE_RULE_CONFIG }, sqlWhere, null);
                 /*SDK-654   hewengao 20161026 end*/
            if (cur != null && cur.getCount() > 0) {
                int idIndex = cur.getColumnIndex(ID);
                int sceneIdIndex = cur.getColumnIndex(SCENE_ID);
                int provinceIndex = cur.getColumnIndex(PROVINCE);
                int operatorIndex = cur.getColumnIndex(OPERATOR);
                int dateIndex = cur.getColumnIndex(EXPIRE_DATE);
                int callIndex = cur.getColumnIndex(FUNC_CALL);
                int accUrlIndex = cur.getColumnIndex(FUNC_ACC_URL);
                int replySmsIndex = cur.getColumnIndex(FUNC_REPLY_SMS);
                int configIndex = cur.getColumnIndex(FUNC_CONFIG);
                int urlsIndex = cur.getColumnIndex(RES_URLS);
                int versionIndex = cur.getColumnIndex(S_VERSION);
                int pageConfigIndex = cur.getColumnIndex(SCENE_PAGE_CONFIG);
                int isdownloadIndex = cur.getColumnIndex(ISDOWNLOAD);
                int sceneRuleVersionIndex = cur.getColumnIndex(SCENERULEVERSION);
                    /*SDK-654   hewengao 20161026 start*/
                int sceneRuleConfigIndex = cur.getColumnIndex(SCENE_RULE_CONFIG);
                    /* SDK-654  hewengao 20161026 end*/
                SceneRule tempConfig = null;
                while (cur.moveToNext()) {
                    tempConfig = new SceneRule();
                    tempConfig.id = cur.getString(idIndex);
                    tempConfig.scene_id = cur.getString(sceneIdIndex);
                    tempConfig.province = cur.getString(provinceIndex);
                    tempConfig.operator = cur.getString(operatorIndex);
                    tempConfig.expire_date = cur.getString(dateIndex);
                    tempConfig.Func_call = cur.getInt(callIndex);
                    tempConfig.Func_acc_url = cur.getInt(accUrlIndex);
                    tempConfig.Func_reply_sms = cur.getInt(replySmsIndex);
                    tempConfig.Func_config = cur.getString(configIndex);
                    tempConfig.res_urls = cur.getString(urlsIndex);
                    tempConfig.s_version = cur.getString(versionIndex);
                    tempConfig.Scene_page_config = cur.getString(pageConfigIndex);
                    tempConfig.isDownload = cur.getInt(isdownloadIndex);
                    tempConfig.sceneruleVersion= cur.getString(sceneRuleVersionIndex);
                    /* SDK-654  hewengao 20161026 start*/
                    tempConfig.mSceneRuleConfig = cur.getString(sceneRuleConfigIndex);
                    /* SDK-654  hewengao 20161026 end*/
                    sceneRuleList.add(tempConfig);
                }

            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "querySceneRuleBySceneId error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return sceneRuleList;
    }

    public static long insertOrUpdate(SceneRule sceneRule,int sceneType) {
        long result = -1;
        ContentValues values = setContentValues(sceneRule,sceneType);
        XyCursor xyCursor = null;
        try {
            if (!StringUtils.isNull(sceneRule.id)) {
                xyCursor = DBManager.query(TABLE_NAME, new String[] {
                    ID, SCENERULEVERSION
                }, ID + " = ? ", new String[] {
                    sceneRule.id
                });
            }
            if (xyCursor != null && xyCursor.getCount() > 0) {
                result = DBManager.update(TABLE_NAME, values, ID + "=? ", new String[] {
                    sceneRule.id
                });
            } else {
                result = DBManager.insert(TABLE_NAME,  values);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertOrUpdate error", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }
        return result;
    }

    public static ContentValues setContentValues(SceneRule sceneRule,int sceneType) {
        ContentValues values = new ContentValues();
        values.put(ID, sceneRule.id);
        values.put(SCENERULEVERSION, sceneRule.sceneruleVersion);
        values.put(SCENE_ID, sceneRule.scene_id);
        values.put(PROVINCE, sceneRule.province);
        values.put(OPERATOR, sceneRule.operator);
        values.put(EXPIRE_DATE, sceneRule.expire_date);
        values.put(FUNC_CALL, sceneRule.Func_call);
        values.put(FUNC_ACC_URL, sceneRule.Func_acc_url);
        values.put(FUNC_REPLY_SMS, sceneRule.Func_reply_sms);
        values.put(FUNC_CONFIG, sceneRule.Func_config);
        values.put(RES_URLS, sceneRule.res_urls);
        values.put(S_VERSION, sceneRule.s_version);
        values.put(SCENE_PAGE_CONFIG, sceneRule.Scene_page_config);
        values.put(ISDOWNLOAD, sceneRule.isDownload);
        values.put(SCENETYPE, sceneType);
       /*SDK-654   hewengao 20161026 start*/
       try {
    	   /*SDK-658 zhaojiangwei 20161101 start */
           HashMap<String, String> map = SmsTitleManager.getBusinessTitleById(Constant.getContext(), sceneRule.scene_id, sceneRule.Scene_page_config, sceneRule.Func_config);
           /*SDK-658 zhaojiangwei 20161101 end */
           if (map != null && !map.isEmpty()) {
               JSONObject jsonObject = new JSONObject(map);
               values.put(SCENE_RULE_CONFIG,jsonObject.toString());
               values.put(FUNC_CONFIG,"");
               values.put(SCENE_PAGE_CONFIG,"");
           }
       }catch (Throwable e){
           LogManager.w(Constant.TAG,"SceneRuleManager setContentValues",e);
       }
        /*SDK-654   hewengao 20161026 end*/
        return values;
    }

    public static void deleteSceneRuleById(String scenid,int sceneType) {
        try {
        	String sqlWhere="";
			if(sceneType == SceneconfigManager.SCENE_TYPE_BUBBLE){
				sqlWhere =SCENE_ID+"=? and "+SCENETYPE+" = "+sceneType;
			}else{
				sqlWhere =SCENE_ID+"=? and "+SCENETYPE+" != "+SceneconfigManager.SCENE_TYPE_BUBBLE;
			}
			DBManager.delete(TABLE_NAME,sqlWhere, new String[] {scenid});
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteSceneRuleById error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }


    public static void deleteAll(){
    	try {
    		DBManager.delete(TABLE_NAME, null,null);
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteAll error: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}
    }
 
    /**
     * 删除重复数据，现将原有数据的FUNC_CALL标记为10，如果与导入数据重复则进行删除
     */
    public static void deleteRepeatData() {
        synchronized (DBManager.dblock) {
            SQLiteDatabase db = null;
            try {
                db = DBManager.getSQLiteDatabase();
                String sql = "DELETE FROM tb_scenerule_config WHERE FUNC_CALL=10 AND scene_id IN (SELECT scene_id FROM tb_scenerule_config WHERE 1=1 GROUP BY scene_id HAVING COUNT(scene_id) > 1)";
                db.execSQL(sql);
            } catch (Throwable e) {
//                e.printStackTrace();
                /*SDK-550 hewengao 20160719 start*/
                LogManager.w(Constant.TAG, "deleteRepeatData: ", e);
                /*SDK-550 hewengao 20160719 end*/

            } finally {
                DBManager.close(db);
            }
        }
    }
    /* SDK-632 hewengao 20161009 start*/
    public static int updateSceneIdUsed(String scendId){
        SQLiteDatabase db = null;
        try {
            db = DBManager.getSQLiteDatabase();
            String sql = "update  " +TABLE_NAME+
                    " set " +ISUSE+" = 1"+
                    " WHERE "+SCENE_ID+" = '"+scendId+"'";
            db.execSQL(sql);
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "updateSceneIdUsed: ", e);
        } finally {
            DBManager.close(db);
        }
        return 0;
    }
    public static int updateSceneRuleUpdateTime(List<SceneRule> listSceneRule){
        SQLiteDatabase db = null;
        try {
            if(listSceneRule == null || listSceneRule.isEmpty()){
                return 0;
            }
            db = DBManager.getSQLiteDatabase();
            db.beginTransaction();
            String sql = "update tb_scenerule_config " +
                    " set " +lAST_UPDATE_TIME+" = "+System.currentTimeMillis()+
                    " WHERE "+ID+" = ?";
            for(SceneRule rule: listSceneRule){
                db.execSQL(sql,new String[]{rule.id});
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "1updateSceneRuleUpdateTime: ", e);
        } finally {
            try {
                if (db != null) {
                    db.setTransactionSuccessful();
                    db.endTransaction();
                }
            }catch (Throwable e){
                LogManager.w(Constant.TAG, "2updateSceneRuleUpdateTime: ", e);
            }
            DBManager.close(db);
        }
        return 0;
    }
    /* SDK-632 hewengao 20161009 end*/
}
